<template>
  <div class="alerts-container">
    <!-- 页面标题和统计卡片 -->
    <div class="page-header">
      <div class="header-background">
        <div class="bg-pattern"></div>
        <div class="bg-gradient"></div>
      </div>
      
      <div class="page-title">
        <div class="title-icon">
          <div class="icon-container" style="width: 36px; height: 36px; background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%); border-radius: 8px; color: white; box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);">
            <el-icon size="20"><Bell /></el-icon>
            <div class="icon-glow"></div>
          </div>
        </div>
        <div class="title-content">
          <div class="title-main">
            <h1>告警管理</h1>
            <div class="title-badge">
              <el-icon><Star /></el-icon>
              <span>Data</span>
            </div>
          </div>
          <p class="page-description">
            <el-icon><Monitor /></el-icon>
            智能监控Data作业告警，提供全面的告警管理和分析功能
          </p>
          <div class="title-meta">
            <div class="meta-item">
              <el-icon><Warning /></el-icon>
              <span>实时监控</span>
            </div>
            <div class="meta-item">
              <el-icon><TrendCharts /></el-icon>
              <span>趋势分析</span>
            </div>
            <div class="meta-item">
              <el-icon><DataAnalysis /></el-icon>
              <span>智能处理</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="page-stats">
        <div class="stat-card total">
          <div class="stat-icon">
            <el-icon><Menu /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.basic_stats?.total_alerts || totalAll || total }}</div>
            <div class="stat-label">告警总数</div>
            <div class="stat-trend">
              <el-icon><Menu /></el-icon>
              <span>全部</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card active">
          <div class="stat-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.basic_stats?.active_alerts || getActiveCount() }}</div>
            <div class="stat-label">活跃告警</div>
            <div class="stat-trend">
              <el-icon><Warning /></el-icon>
              <span>需关注</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card resolved">
          <div class="stat-icon">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.basic_stats?.resolved_alerts || getResolvedCount() }}</div>
            <div class="stat-label">已解决</div>
            <div class="stat-trend">
              <el-icon><Check /></el-icon>
              <span>{{ stats.basic_stats?.resolution_rate || 0 }}%</span>
            </div>
          </div>
        </div>

        <div class="stat-card escalated">
          <div class="stat-icon">
            <el-icon><Top /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.basic_stats?.escalated_alerts || getEscalatedCount() }}</div>
            <div class="stat-label">已升级</div>
            <div class="stat-trend">
              <el-icon><Top /></el-icon>
              <span>优先级</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
            <div class="search-actions">
              <el-button type="primary" size="small" @click="toggleView">
                <el-icon><DataAnalysis /></el-icon>
                {{ currentView === 'dashboard' ? '隐藏' : '显示' }}仪表板
              </el-button>
            </div>
          </div>
        </template>
        <el-form :model="searchForm" class="search-form" inline>
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="作业名称">
                <el-input
                  v-model="searchForm.job_name"
                  placeholder="请输入作业名称"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
              
              <el-form-item v-show="showAdvancedFilters" label="告警类型">
                <el-select v-model="searchForm.alert_type" placeholder="选择告警类型" clearable style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option label="首次失败" value="FIRST_FAILURE" />
                  <el-option label="重试失败" value="RETRY_FAILURE" />
                  <el-option label="最终失败" value="FINAL_FAILURE" />
                  <el-option label="已恢复" value="RECOVERED" />
                  <el-option label="触发中" value="FIRING" />
                  <el-option label="已解决" value="RESOLVED" />
                  <el-option label="Alertmanager" value="ALERTMANAGER" />
                </el-select>
              </el-form-item>

              <el-form-item v-show="showAdvancedFilters" label="严重程度">
                <el-select v-model="searchForm.severity" placeholder="选择严重程度" clearable style="width: 130px">
                  <el-option label="全部" value="" />
                  <el-option label="紧急" value="emergency">
                    <el-tag type="danger" size="small">紧急</el-tag>
                  </el-option>
                  <el-option label="严重" value="critical">
                    <el-tag type="danger" size="small">严重</el-tag>
                  </el-option>
                  <el-option label="异常" value="exception">
                    <el-tag type="warning" size="small">异常</el-tag>
                  </el-option>
                  <el-option label="警告" value="warning">
                    <el-tag type="warning" size="small">警告</el-tag>
                  </el-option>
                  <el-option label="信息" value="info">
                    <el-tag type="info" size="small">信息</el-tag>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="活跃" value="ACTIVE" />
                  <el-option label="已解决" value="RESOLVED" />
                  <el-option label="已升级" value="ESCALATED" />
                  <el-option label="已静默" value="SILENCED" />
                  <el-option label="触发中" value="FIRING" />
                </el-select>
              </el-form-item>

              <el-form-item v-show="showAdvancedFilters" label="时间范围">
                <el-select v-model="searchForm.time_range" placeholder="选择时间范围" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="今天" value="today" />
                  <el-option label="本周" value="week" />
                  <el-option label="本月" value="month" />
                </el-select>
              </el-form-item>
            </div>
          
            <div class="search-form-actions">
              <el-button @click="showAdvancedFilters = !showAdvancedFilters">
                <el-icon>
                  <component :is="showAdvancedFilters ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ showAdvancedFilters ? '收起筛选' : '高级筛选' }}
              </el-button>
              <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
              <el-button type="info" @click="showFieldSelector = !showFieldSelector" class="field-btn">
                <el-icon>
                  <component :is="showFieldSelector ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                字段设置
              </el-button>
            </div>
          </div>
        </el-form>
        
        <!-- 字段设置面板 -->
        <transition name="field-panel">
          <div v-if="showFieldSelector" class="field-selector-panel">
            <div class="field-sorter">
              <div class="sorter-header">
                <h4>字段排序设置</h4>
                <p class="sorter-description">使用上下箭头调整字段显示顺序，勾选要显示的字段</p>
              </div>
              <div class="field-list-sortable">
                <div
                  v-for="(field, index) in sortedFields"
                  :key="field.value"
                  class="field-item"
                  :class="{ 'field-disabled': !selectedFields.includes(field.value) }"
                >
                  <div class="field-drag-handle">
                    <span class="drag-icon">⋮⋮</span>
                  </div>
                  <el-checkbox
                    v-model="selectedFields"
                    :value="field.value"
                    :disabled="field.required"
                    class="field-checkbox"
                  >
                    <span class="field-label">{{ field.label }}</span>
                    <span v-if="field.required" class="required-mark">*</span>
                  </el-checkbox>
                  <div class="field-group-tag">
                    <el-tag size="small" :type="getGroupTagType(field.group)">
                      {{ getGroupTitle(field.group) }}
                    </el-tag>
                  </div>
                  <div class="field-sort-controls">
                    <el-button
                      size="small"
                      :disabled="index === 0"
                      @click="moveFieldUp(index)"
                      circle
                      type="primary"
                      plain
                    >
                      ↑
                    </el-button>
                    <el-button
                      size="small"
                      :disabled="index === sortedFields.length - 1"
                      @click="moveFieldDown(index)"
                      circle
                      type="primary"
                      plain
                    >
                      ↓
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 字段设置操作按钮 -->
            <div class="field-actions">
              <el-button type="primary" @click="saveCurrentFieldSettings">
                <el-icon><Check /></el-icon>
                保存设置
              </el-button>
              <el-button @click="resetFieldSettings">
                <el-icon><Refresh /></el-icon>
                重置默认
              </el-button>
              <el-button @click="showFieldSelector = false">
                <el-icon><Close /></el-icon>
                关闭
              </el-button>
            </div>
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 告警仪表板 -->
    <transition name="dashboard">
      <div v-show="currentView === 'dashboard'" class="dashboard-section">
        <!-- 告警类型筛选器 -->
        <el-card shadow="hover" class="dashboard-filter-card" style="margin-bottom: 20px;">
          <div class="dashboard-filter">
            <div class="filter-label">
              <el-icon><Filter /></el-icon>
              <span>告警类型筛选：</span>
            </div>
            <el-checkbox-group v-model="selectedAlertTypes" class="alert-type-checkboxes">
              <el-checkbox v-for="type in allAlertTypes" :key="type.value" :value="type.value" :label="type.label">
                {{ type.label }}
              </el-checkbox>
            </el-checkbox-group>
            <div class="filter-actions">
              <el-button size="small" @click="selectedAlertTypes = allAlertTypes.map(t => t.value)">全选</el-button>
              <el-button size="small" @click="selectedAlertTypes = []">清空</el-button>
            </div>
          </div>
        </el-card>

        <!-- 2x2 仪表板网格 -->
        <el-row :gutter="20">
          <!-- 第一行 -->
          <!-- 严重程度分布 -->
          <el-col :span="12">
            <el-card shadow="hover" class="dashboard-card">
              <template #header>
                <div class="card-header">
                  <div class="header-title">
                    <el-icon><Warning /></el-icon>
                    <span>严重程度分布</span>
                  </div>
                </div>
              </template>
              <div class="chart-container" style="height: 300px;">
                <el-empty v-if="!stats.severity_distribution?.length" description="暂无数据" />
                <div v-else class="severity-chart">
                  <div v-for="item in stats.severity_distribution" :key="item.severity" class="severity-item">
                    <div class="severity-info">
                      <el-tag :type="getSeverityTagType(item.severity)" size="small">
                        {{ getSeverityLabel(item.severity) }}
                      </el-tag>
                      <span class="severity-count">{{ item.count }}</span>
                    </div>
                    <div class="severity-bar">
                      <div 
                        class="severity-fill" 
                        :class="`severity-${item.severity}`"
                        :style="{ width: `${(item.count / Math.max(...stats.severity_distribution.map(s => s.count))) * 100}%` }"
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 告警类型分布 -->
          <el-col :span="12">
            <el-card shadow="hover" class="dashboard-card">
              <template #header>
                <div class="card-header">
                  <div class="header-title">
                    <el-icon><DataLine /></el-icon>
                    <span>告警类型分布</span>
                  </div>
                </div>
              </template>
              <div class="chart-container" style="height: 300px;">
                <el-empty v-if="!stats.type_distribution?.length" description="暂无数据" />
                <div v-else class="type-chart">
                  <div v-for="item in stats.type_distribution" :key="item.alert_type" class="type-item">
                    <div class="type-info">
                      <el-tag :type="getAlertTypeType(item.alert_type)" size="small">
                        {{ getAlertTypeLabel(item.alert_type) }}
                      </el-tag>
                      <span class="type-count">{{ item.count }}</span>
                    </div>
                    <div class="type-bar">
                      <div 
                        class="type-fill"
                        :style="{ width: `${(item.count / Math.max(...stats.type_distribution.map(t => t.count))) * 100}%` }"
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <!-- 时段分布 -->
          <el-col :span="12">
            <el-card shadow="hover" class="dashboard-card">
              <template #header>
                <div class="card-header">
                  <div class="header-title">
                    <el-icon><Clock /></el-icon>
                    <span>24小时分布</span>
                  </div>
                </div>
              </template>
              <div class="chart-container" style="height: 300px;">
                <el-empty v-if="!stats.hourly_trend?.length" description="暂无数据" />
                <div v-else class="hourly-line-chart">
                  <div class="chart-grid">
                    <!-- Y轴刻度线 -->
                    <div class="y-axis-lines">
                      <div class="grid-line" v-for="i in 5" :key="i"></div>
                    </div>
                    
                    <!-- 折线图容器 -->
                    <div class="line-container">
                      <svg class="line-svg" viewBox="0 0 1000 200" preserveAspectRatio="none">
                        <!-- 渐变定义 -->
                        <defs>
                          <linearGradient id="lineGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                            <stop offset="0%" style="stop-color:#409eff;stop-opacity:0.3" />
                            <stop offset="100%" style="stop-color:#409eff;stop-opacity:0.05" />
                          </linearGradient>
                        </defs>
                        
                        <!-- 面积填充 -->
                        <path 
                          :d="getLineChartPath(true)" 
                          fill="url(#lineGradient)" 
                          stroke="none"
                        />
                        
                        <!-- 折线 -->
                        <path 
                          :d="getLineChartPath(false)" 
                          fill="none" 
                          stroke="#409eff" 
                          stroke-width="3"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                        />
                        
                        <!-- 数据点 -->
                        <circle
                          v-for="(item, index) in getHourlyDistribution()" 
                          :key="index"
                          :cx="(index / 23) * 1000"
                          :cy="200 - (item.count / Math.max(...getHourlyDistribution().map(h => h.count)) * 180)"
                          r="4"
                          fill="#409eff"
                          class="data-point"
                        >
                          <title>{{ item.hour }}时: {{ item.count }}次</title>
                        </circle>
                      </svg>
                    </div>
                  </div>
                  
                  <!-- X轴标签 -->
                  <div class="x-axis-labels">
                    <span v-for="h in [0, 4, 8, 12, 16, 20, 23]" :key="h" class="x-label">
                      {{ h }}:00
                    </span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 作业热点TOP10 -->
          <el-col :span="12">
            <el-card shadow="hover" class="dashboard-card">
              <template #header>
                <div class="card-header">
                  <div class="header-title">
                    <el-icon><Histogram /></el-icon>
                    <span>作业热点 TOP10</span>
                  </div>
                  <el-button type="text" size="small" @click="refreshDashboard">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </div>
              </template>
              <div class="chart-container" style="height: 300px;">
                <el-empty v-if="!hotspots.job_hotspots?.length" description="暂无数据" />
                <div v-else class="hotspot-chart">
                  <div v-for="(job, index) in hotspots.job_hotspots.slice(0, 10)" :key="job.job_name" class="job-hotspot-item">
                    <div class="job-rank">{{ index + 1 }}</div>
                    <div class="job-content">
                      <div class="job-name-wrapper">
                        <span class="job-name">{{ job.job_name }}</span>
                        <div class="job-tags">
                          <el-tag size="small" :type="job.active_count > 0 ? 'danger' : 'success'">
                            {{ job.alert_count }}次
                          </el-tag>
                          <el-tag v-if="job.active_count > 0" size="small" type="warning">
                            {{ job.active_count }}活跃
                          </el-tag>
                        </div>
                      </div>
                      <div class="job-bar">
                        <div 
                          class="job-fill"
                          :class="{ 'has-active': job.active_count > 0 }"
                          :style="{ width: `${(job.alert_count / Math.max(...hotspots.job_hotspots.map(j => j.alert_count))) * 100}%` }"
                        ></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </transition>

    <!-- 批量操作区域 -->
    <div class="batch-actions-bar" v-if="selectedAlerts.length > 0">
      <div class="batch-info-compact">
        <el-icon class="selected-icon"><Select /></el-icon>
        <span>已选择<strong>{{ selectedAlerts.length }}</strong>条告警</span>
      </div>
      <div class="batch-divider">|</div>
      <div class="batch-buttons-compact">
        <el-button type="success" class="batch-btn-compact" @click="handleBatchResolve">
          <el-icon><Check /></el-icon>
          批量解决
        </el-button>
        <el-button type="warning" class="batch-btn-compact" @click="handleBatchSilence">
          <el-icon><Mute /></el-icon>
          批量静默
        </el-button>
        <el-button type="danger" class="batch-btn-compact" @click="handleBatchEscalate">
          <el-icon><Top /></el-icon>
          批量升级
        </el-button>
        <el-button type="info" class="batch-btn-compact" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 告警列表 -->
    <div v-show="currentView === 'list'" class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>告警列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <div class="table-info">
                <!-- 合并的分页信息控制 -->
                <div class="pagination-control-wrapper" @click="paginationExpanded = !paginationExpanded">
                  <span class="page-count">本页 {{ alerts.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">{{ currentPage }}/{{ Math.ceil(total / pageSize) }}</span>
                  <el-icon class="pagination-icon" :class="{ 'expanded': paginationExpanded }">
                    <ArrowDown />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>
        <div class="table-container">
          <el-table
            v-loading="loading"
            :data="alerts"
            :default-sort="{ prop: 'creation_time', order: 'descending' }"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
            style="width: 100%;"
            :row-key="row => row.id"
            :height="600"
            table-layout="fixed"
            :row-class-name="getRowClassName"
            class="enhanced-table"
          >
            <!-- 选择列 -->
            <el-table-column type="selection" width="55" />
            
            <!-- 动态列 -->
            <template v-for="field in visibleFields" :key="field.value">
              <el-table-column
                v-if="selectedFields.includes(field.value)"
                :prop="field.value"
                :width="getColumnWidth(field.value)"
                :min-width="getColumnMinWidth(field.value)"
                :show-overflow-tooltip="getFieldShowOverflow(field.value)"
                :sortable="isTimeSortableField(field.value) ? 'custom' : false"
                :sort-orders="['descending', 'ascending', null]"
              >
                <template #header>
                  <div class="column-header-simple">
                    {{ field.label }}
                  </div>
                </template>
                
                <template #default="{ row }">
                  <!-- 作业名称字段 -->
                  <div v-if="field.value === 'job_name'" class="job-name-cell-alert">
                    <span class="job-name-text-alert">{{ row.job_name }}</span>
                    <el-tooltip content="复制作业名称" placement="top">
                      <el-button 
                        type="info"
                        size="small" 
                        @click.stop="handleCopyJobName(row.job_name)" 
                        circle
                        class="copy-btn-alert"
                      >
                        <el-icon><DocumentCopy /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                  
                  <!-- 告警类型字段 -->
                  <div v-else-if="field.value === 'alert_type'" class="field-content">
                    <el-tag :type="getAlertTypeType(row.alert_type)" size="small">
                      {{ getAlertTypeLabel(row.alert_type) }}
                    </el-tag>
                  </div>
                  
                  <!-- 状态字段 -->
                  <div v-else-if="field.value === 'status'" class="status-container">
                    <el-tag :type="getStatusType(row.status)" size="small" class="status-tag">
                      <el-icon v-if="row.status === 'ACTIVE'" class="status-icon"><Warning /></el-icon>
                      <el-icon v-else-if="row.status === 'RESOLVED'" class="status-icon"><Check /></el-icon>
                      <el-icon v-else-if="row.status === 'ESCALATED'" class="status-icon"><Top /></el-icon>
                      <el-icon v-else-if="row.status === 'SILENCED'" class="status-icon"><Mute /></el-icon>
                      <span class="status-text">{{ getStatusLabel(row.status) }}</span>
                    </el-tag>
                    <div class="status-indicator" :class="`indicator-${row.status?.toLowerCase()}`"></div>
                  </div>
                  
                  <!-- 告警信息字段 -->
                  <div v-else-if="field.value === 'message'" class="copyable-field" @click="copyToClipboard(row.message, '告警信息')">
                    <el-text size="small">{{ row.message || '-' }}</el-text>
                    <div class="copy-hint">
                      <el-icon><Document /></el-icon>
                    </div>
                  </div>
                  
                  <!-- 时间字段 -->
                  <el-text v-else-if="['creation_time', 'starts_at', 'ends_at', 'resolved_time', 'last_send_time', 'silence_until', 'processed_at'].includes(field.value)" 
                           size="small">
                    {{ formatTime(row[field.value]) }}
                  </el-text>
                  
                  <!-- 发送次数字段 -->
                  <el-text v-else-if="field.value === 'send_count'" 
                           size="small" 
                           :type="row.send_count > 3 ? 'danger' : (row.send_count > 1 ? 'warning' : 'success')">
                    {{ row.send_count || 0 }}
                  </el-text>
                  
                  <!-- 升级原因字段 -->
                  <div v-else-if="field.value === 'escalation_reason'" class="copyable-field" @click="copyToClipboard(row.escalation_reason, '升级原因')">
                    <el-text size="small" type="warning">{{ row.escalation_reason || '-' }}</el-text>
                    <div class="copy-hint">
                      <el-icon><Document /></el-icon>
                    </div>
                  </div>
                  
                  <!-- 告警标题字段 -->
                  <div v-else-if="field.value === 'alert_title'" class="copyable-field" @click="copyToClipboard(row.alert_title, '告警标题')">
                    <el-text size="small">{{ row.alert_title || row.message || '-' }}</el-text>
                    <div class="copy-hint">
                      <el-icon><Document /></el-icon>
                    </div>
                  </div>
                  
                  <!-- 默认字段 -->
                  <el-text v-else size="small">
                    {{ row[field.value] || '-' }}
                  </el-text>
                </template>
              </el-table-column>
            </template>
            
            <!-- 操作列 -->
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      size="small"
                      @click="viewDetails(row)"
                      circle
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="解决告警" placement="top">
                    <el-button
                      v-if="row.status !== 'RESOLVED'"
                      type="success"
                      size="small"
                      @click="handleResolve(row)"
                      circle
                    >
                      <el-icon><Check /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="静默告警" placement="top">
                    <el-button
                      v-if="row.status === 'ACTIVE'"
                      type="warning"
                      size="small"
                      @click="handleSilence(row)"
                      circle
                    >
                      <el-icon><Mute /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <!-- 更多操作下拉菜单 -->
                  <el-dropdown @command="(command) => handleMoreAction(command, row)">
                    <el-button type="info" size="small" circle>
                      <el-icon><MoreFilled /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item 
                          v-if="row.status === 'ACTIVE'"
                          command="escalate"
                        >
                          <el-icon><Top /></el-icon>
                          升级告警
                        </el-dropdown-item>
                        <el-dropdown-item 
                          command="delete"
                          divided
                        >
                          <el-icon><Delete /></el-icon>
                          删除告警
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 可折叠分页 -->
        <div v-show="paginationExpanded" class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="enhanced-pagination"
          />
        </div>
      </el-card>
    </div>

    <!-- 告警详情对话框 -->
    <AlertDetailDialog
      v-model="showDetailDialog"
      :alert="currentAlert"
      @success="fetchAlerts"
    />

    <!-- 告警升级对话框 -->
    <AlertEscalateDialog
      v-model="showEscalateDialog"
      :alert="currentAlert"
      @success="fetchAlerts"
    />

    <!-- 告警静默对话框 -->
    <AlertSilenceDialog
      v-model="showSilenceDialog"
      :alert="currentAlert"
      @success="fetchAlerts"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAlertsStore } from '@/stores/alerts'
import { useAppStore } from '@/stores/app'
import { ElMessage, ElMessageBox } from 'element-plus'
import { componentLogger } from '@/utils/logger'
import { copyToClipboard as copyText } from '@/utils/clipboard'
import dayjs from 'dayjs'
import { debounce } from 'lodash-es'
import FieldSelector from '@/components/FieldSelector.vue'
import AlertDetailDialog from './components/AlertDetailDialog.vue'
import AlertEscalateDialog from './components/AlertEscalateDialog.vue'
import AlertSilenceDialog from './components/AlertSilenceDialog.vue'

const alertsStore = useAlertsStore()
const appStore = useAppStore()
const { sidebarCollapsed } = storeToRefs(appStore)

// 响应式数据
const showDetailDialog = ref(false)
const showEscalateDialog = ref(false)
const showSilenceDialog = ref(false)
const currentAlert = ref(null)
const paginationExpanded = ref(false)
const showFieldSelector = ref(false)
const currentView = ref('list') // 'list' | 'dashboard'
const trendPeriod = ref('daily')
const showAdvancedFilters = ref(false)

// 告警类型过滤（仪表板用）
const selectedAlertTypes = ref([
  'FIRST_FAILURE', 'RETRY_FAILURE', 'FINAL_FAILURE',
  'RECOVERED', 'OTHER', 'FIRING', 'RESOLVED', 'ALERTMANAGER'
])

// 所有可用的告警类型
const allAlertTypes = [
  { label: '首次失败', value: 'FIRST_FAILURE' },
  { label: '重试失败', value: 'RETRY_FAILURE' },
  { label: '最终失败', value: 'FINAL_FAILURE' },
  { label: '已恢复', value: 'RECOVERED' },
  { label: '其他', value: 'OTHER' },
  { label: '触发中', value: 'FIRING' },
  { label: '已解决', value: 'RESOLVED' },
  { label: 'Alertmanager', value: 'ALERTMANAGER' }
]

// 字段选择
const selectedFields = ref([
  'job_name', 'alert_type', 'alert_title', 'status', 'creation_time', 'send_count'
])

// 字段配置（包含新增的Alertmanager兼容字段）
const fieldConfig = {
  basic: [
    { value: 'job_name', label: '作业名称', required: true, default: true, group: 'basic' },
    { value: 'job_id', label: '作业ID', group: 'basic' },
    { value: 'alert_title', label: '告警标题', default: true, group: 'basic' },
    { value: 'message', label: '告警内容', group: 'basic' },
    { value: 'alertname', label: '告警名称', group: 'basic' }
  ],
  status: [
    { value: 'alert_type', label: '告警类型', default: true, group: 'status' },
    { value: 'status', label: '状态', default: true, group: 'status' },
    { value: 'severity', label: '严重程度', default: true, group: 'status' },
    { value: 'send_count', label: '发送次数', default: true, group: 'status' },
    { value: 'is_processed', label: '是否已处理', group: 'status' }
  ],
  alertmanager: [
    { value: 'alert_id', label: '告警ID', group: 'alertmanager' },
    { value: 'instance', label: '实例地址', group: 'alertmanager' },
    { value: 'hostname', label: '主机名', group: 'alertmanager' },
    { value: 'service', label: '服务名称', group: 'alertmanager' },
    { value: 'device', label: '设备名称', group: 'alertmanager' },
    { value: 'cluster_id', label: '集群ID', group: 'alertmanager' }
  ],
  time: [
    { value: 'creation_time', label: '创建时间', default: true, group: 'time' },
    { value: 'starts_at', label: '告警开始时间', group: 'time' },
    { value: 'ends_at', label: '告警结束时间', group: 'time' },
    { value: 'resolved_time', label: '解决时间', group: 'time' },
    { value: 'last_send_time', label: '最后发送时间', group: 'time' },
    { value: 'silence_until', label: '静默截止时间', group: 'time' },
    { value: 'processed_at', label: '处理时间', group: 'time' }
  ],
  other: [
    { value: 'escalation_reason', label: '升级原因', group: 'other' },
    { value: 'recovery_attempts', label: '恢复尝试次数', group: 'other' },
    { value: 'max_recovery_attempts', label: '最大恢复次数', group: 'other' },
    { value: 'processed_by', label: '处理人', group: 'other' },
    { value: 'notification_channels', label: '通知渠道', group: 'other' }
  ]
}

// 计算属性
const allFields = computed(() => {
  return Object.values(fieldConfig).flat()
})

const sortedFields = computed(() => {
  return allFields.value.sort((a, b) => {
    const aIndex = selectedFields.value.indexOf(a.value)
    const bIndex = selectedFields.value.indexOf(b.value)
    return aIndex - bIndex
  })
})

const visibleFields = computed(() => {
  return allFields.value.filter(field => selectedFields.value.includes(field.value))
})

// 统计方法（优先使用全部数据的统计）
const getActiveCount = () => {
  if (statusStats.value && Object.keys(statusStats.value).length > 0) {
    return statusStats.value['ACTIVE'] || 0
  }
  return alerts.value.filter(item => item.status === 'ACTIVE').length
}

const getResolvedCount = () => {
  if (statusStats.value && Object.keys(statusStats.value).length > 0) {
    return statusStats.value['RESOLVED'] || 0
  }
  return alerts.value.filter(item => item.status === 'RESOLVED').length
}

const getEscalatedCount = () => {
  if (statusStats.value && Object.keys(statusStats.value).length > 0) {
    return statusStats.value['ESCALATED'] || 0
  }
  return alerts.value.filter(item => item.status === 'ESCALATED').length
}

const getSilencedCount = () => {
  if (statusStats.value && Object.keys(statusStats.value).length > 0) {
    return statusStats.value['SILENCED'] || 0
  }
  return alerts.value.filter(item => item.status === 'SILENCED').length
}

// 字段相关方法
const getFieldIcon = (fieldValue) => {
  const iconMap = {
    'job_name': 'Document',
    'alert_type': 'Warning',
    'message': 'InfoFilled',
    'creation_time': 'Clock',
    'status': 'CircleCheck'
  }
  return iconMap[fieldValue] || 'Menu'
}

const getFieldSubtitle = (fieldValue) => {
  const subtitleMap = {
    'job_name': 'Job Name',
    'alert_type': 'Alert Type',
    'message': 'Alert Message',
    'creation_time': 'Created At',
    'status': 'Status'
  }
  return subtitleMap[fieldValue] || 'Field'
}

const getColumnWidth = (fieldValue) => {
  const widthMap = {
    'job_name': 350,  // 作业名称使用固定宽度，不换行不隐藏
    'alert_type': 120,
    'message': 300,
    'creation_time': 180,
    'status': 100
  }
  return widthMap[fieldValue] || 150
}

const getColumnMinWidth = (fieldValue) => {
  const minWidthMap = {
    'job_name': undefined,  // 作业名称使用固定宽度，不需要min-width
    'alert_type': 100,
    'message': 200,
    'status': 80,
    // 时间字段统一设置为180px，避免换行
    'creation_time': 180,
    'starts_at': 180,
    'ends_at': 180,
    'resolved_time': 180,
    'last_send_time': 180,
    'silence_until': 180,
    'processed_at': 180
  }
  return minWidthMap[fieldValue] || 120
}

const getGroupTagType = (group) => {
  const typeMap = {
    'basic': 'primary',
    'status': 'success',
    'time': 'warning',
    'other': 'info'
  }
  return typeMap[group] || 'info'
}

const getGroupTitle = (group) => {
  const titleMap = {
    'basic': '基础信息',
    'status': '状态信息',
    'time': '时间信息',
    'other': '其他信息'
  }
  return titleMap[group] || '其他'
}

const moveFieldUp = (index) => {
  if (index > 0) {
    const fields = [...sortedFields.value]
    ;[fields[index], fields[index - 1]] = [fields[index - 1], fields[index]]
    selectedFields.value = fields.map(f => f.value)
  }
}

const moveFieldDown = (index) => {
  if (index < sortedFields.value.length - 1) {
    const fields = [...sortedFields.value]
    ;[fields[index], fields[index + 1]] = [fields[index + 1], fields[index]]
    selectedFields.value = fields.map(f => f.value)
  }
}

const saveCurrentFieldSettings = () => {
  localStorage.setItem('alerts_selected_fields', JSON.stringify(selectedFields.value))
  ElMessage.success('字段设置已保存')
  showFieldSelector.value = false
}

const resetFieldSettings = () => {
  selectedFields.value = ['job_name', 'alert_type', 'message', 'creation_time', 'status']
  localStorage.removeItem('alerts_selected_fields')
  ElMessage.success('字段设置已重置')
}

const getRowClassName = ({ row }) => {
  if (row.status === 'RESOLVED') return 'row-success'
  if (row.status === 'ACTIVE') return 'row-danger'
  if (row.status === 'ESCALATED') return 'row-warning'
  if (row.status === 'SILENCED') return 'row-info'
  return ''
}

// 告警类型和状态标签方法
const getAlertTypeType = (alertType) => {
  return alertsStore.getAlertTypeType(alertType)
}

const getStatusType = (status) => {
  return alertsStore.getStatusType(status)
}

const getAlertTypeLabel = (alertType) => {
  const labelMap = {
    'FIRST_FAILURE': '首次失败',
    'RETRY_FAILURE': '重试失败',
    'FINAL_FAILURE': '最终失败',
    'RECOVERED': '已恢复',
    'FIRING': '触发中',
    'RESOLVED': '已解决',
    'ALERTMANAGER': 'Alertmanager',
    'OTHER': '其他'
  }
  return labelMap[alertType] || alertType
}

const getStatusLabel = (status) => {
  const labelMap = {
    'ACTIVE': '活跃',
    'RESOLVED': '已解决',
    'ESCALATED': '已升级',
    'SILENCED': '已静默',
    'FIRING': '触发中'
  }
  return labelMap[status] || status
}

// 复制到剪贴板功能 - 使用统一工具
const copyToClipboard = async (text, fieldName = '内容') => {
  await copyText(text, fieldName)
}

// 复制作业名称
const handleCopyJobName = async (jobName) => {
  if (!jobName) {
    ElMessage.warning('作业名称为空，无法复制')
    return
  }
  await copyText(jobName, '作业名称', false)
  ElMessage.success({
    message: `作业名称已复制: ${jobName}`,
    duration: 2000
  })
}

// 计算属性
const alerts = computed(() => alertsStore.alerts)
const loading = computed(() => alertsStore.loading)
const total = computed(() => alertsStore.total)
const totalAll = computed(() => alertsStore.totalAll)
const statusStats = computed(() => alertsStore.statusStats)
const stats = computed(() => alertsStore.stats)
const trends = computed(() => alertsStore.trends)
const hotspots = computed(() => alertsStore.hotspots)
const selectedAlerts = computed(() => alertsStore.selectedAlerts)

const currentPage = computed({
  get: () => alertsStore.currentPage,
  set: (value) => { alertsStore.currentPage = value }
})
const pageSize = computed({
  get: () => alertsStore.pageSize,
  set: (value) => { alertsStore.pageSize = value }
})
const searchForm = computed(() => alertsStore.searchForm)

// 状态类型映射
const levelTypeCache = new Map()
const getLevelType = (level) => {
  if (levelTypeCache.has(level)) {
    return levelTypeCache.get(level)
  }
  const levelMap = {
    'INFO': 'success',
    'WARN': 'warning',
    'ERROR': 'danger'
  }
  const result = levelMap[level] || 'info'
  levelTypeCache.set(level, result)
  return result
}

// 时间格式化
const timeFormatCache = new Map()
const formatTime = (time) => {
  if (!time) return '-'
  if (timeFormatCache.has(time)) {
    return timeFormatCache.get(time)
  }
  const formatted = dayjs(time).format('YYYY-MM-DD HH:mm:ss')
  timeFormatCache.set(time, formatted)
  return formatted
}

// 判断字段是否可排序（时间字段）
const isTimeSortableField = (fieldValue) => {
  const sortableFields = ['creation_time', 'starts_at', 'ends_at', 'resolved_time', 'last_send_time']
  return sortableFields.includes(fieldValue)
}

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  // 字段映射：前端字段名 -> 后端字段名
  const fieldMapping = {
    'creation_time': 'sent_time',
    'starts_at': 'starts_at',
    'ends_at': 'ends_at',
    'resolved_time': 'resolved_time',
    'last_send_time': 'last_send_time'
  }
  
  if (!prop || !order) {
    // 取消排序，恢复默认（按创建时间降序）
    alertsStore.searchForm.sort_by = 'sent_time'
    alertsStore.searchForm.sort_order = 'DESC'
  } else {
    // 设置排序
    const backendField = fieldMapping[prop] || prop
    alertsStore.searchForm.sort_by = backendField
    alertsStore.searchForm.sort_order = order === 'ascending' ? 'ASC' : 'DESC'
  }
  
  // 重置到第一页并刷新数据
  alertsStore.currentPage = 1
  fetchAlerts()
}

// 方法
const handleSearch = () => {
  currentPage.value = 1
  fetchAlerts()
}

const handleReset = () => {
  alertsStore.resetSearch()
  fetchAlerts()
}

const handleRefresh = () => {
  fetchAlerts()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  fetchAlerts()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchAlerts()
}

const fetchAlerts = async () => {
  try {
    // 如果还没有全部数据统计，先获取
    if (!alertsStore.totalAll) {
      await alertsStore.fetchAllStats()
    }
    
    await alertsStore.fetchAlerts()
  } catch (error) {
    componentLogger.error('获取告警列表失败:', error)
  }
}

const viewDetails = (alert) => {
  currentAlert.value = alert
  showDetailDialog.value = true
}

// 告警操作方法
const handleResolve = async (alert) => {
  try {
    const { value } = await ElMessageBox.prompt(
      `将告警 "${alert.job_name}" 标记为已解决`,
      '解决告警',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入解决原因（可选）',
        inputType: 'textarea'
      }
    )
    
    await alertsStore.resolveAlert(alert.id, {
      resolution_reason: value || '手动解决',
      resolved_by: '用户'
    })
    
    await fetchAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('解决告警失败:', error)
    }
  }
}

const handleSilence = (alert) => {
  currentAlert.value = alert
  showSilenceDialog.value = true
}

const handleEscalate = (alert) => {
  currentAlert.value = alert
  showEscalateDialog.value = true
}

const handleDelete = async (alert) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除告警 "${alert.job_name}" 吗？此操作不可撤销！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    await alertsStore.deleteAlert(alert.id)
    await fetchAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('删除告警失败:', error)
    }
  }
}

// 批量操作方法
const handleBatchResolve = async () => {
  try {
    const { value } = await ElMessageBox.prompt(
      `批量解决 ${selectedAlerts.value.length} 个告警`,
      '批量解决',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入解决原因（可选）',
        inputType: 'textarea'
      }
    )
    
    const alertIds = selectedAlerts.value.map(alert => alert.id)
    await alertsStore.batchOperation(alertIds, 'resolve', {
      resolution_reason: value || '批量解决',
      resolved_by: '用户'
    })
    
    alertsStore.selectedAlerts = []
    await fetchAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('批量解决失败:', error)
    }
  }
}

const handleBatchSilence = async () => {
  try {
    const { value } = await ElMessageBox.prompt(
      `批量静默 ${selectedAlerts.value.length} 个告警`,
      '批量静默',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '静默时长（分钟），默认60分钟',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效的数字'
      }
    )
    
    const minutes = parseInt(value) || 60
    const alertIds = selectedAlerts.value.map(alert => alert.id)
    await alertsStore.batchOperation(alertIds, 'silence', {
      minutes,
      silence_reason: '批量静默',
      silenced_by: '用户'
    })
    
    alertsStore.selectedAlerts = []
    await fetchAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('批量静默失败:', error)
    }
  }
}

const handleBatchEscalate = async () => {
  try {
    const { value } = await ElMessageBox.prompt(
      `批量升级 ${selectedAlerts.value.length} 个告警`,
      '批量升级',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入升级原因',
        inputType: 'textarea'
      }
    )
    
    const alertIds = selectedAlerts.value.map(alert => alert.id)
    await alertsStore.batchOperation(alertIds, 'escalate', {
      escalation_reason: value || '批量升级'
    })
    
    alertsStore.selectedAlerts = []
    await fetchAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('批量升级失败:', error)
    }
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedAlerts.value.length} 个告警吗？此操作不可撤销！`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const alertIds = selectedAlerts.value.map(alert => alert.id)
    await alertsStore.batchOperation(alertIds, 'delete')
    
    alertsStore.selectedAlerts = []
    await fetchAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('批量删除失败:', error)
    }
  }
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  alertsStore.selectedAlerts = selection
}

// 更多操作处理
const handleMoreAction = (command, row) => {
  switch (command) {
    case 'escalate':
      handleEscalate(row)
      break
    case 'delete':
      handleDelete(row)
      break
  }
}

// 字段变化处理 - 使用防抖优化性能
const handleFieldChange = debounce((fields) => {
  selectedFields.value = fields
  localStorage.setItem('alerts_selected_fields', JSON.stringify(fields))
}, 100)

// 仪表板相关方法
const fetchStats = async () => {
  try {
    await alertsStore.fetchStats('week', selectedAlertTypes.value)
  } catch (error) {
    componentLogger.error('获取统计数据失败:', error)
  }
}

const fetchTrends = async () => {
  try {
    await alertsStore.fetchTrends(trendPeriod.value, 7)
  } catch (error) {
    componentLogger.error('获取趋势数据失败:', error)
  }
}

const fetchHotspots = async () => {
  try {
    await alertsStore.fetchHotspots(7, 10, selectedAlertTypes.value)
  } catch (error) {
    componentLogger.error('获取热点数据失败:', error)
  }
}

const formatTrendTime = (timeStr) => {
  if (!timeStr) return '-'
  
  if (trendPeriod.value === 'hourly') {
    return dayjs(timeStr).format('MM-DD HH:mm')
  } else if (trendPeriod.value === 'weekly') {
    return `第${timeStr}周`
  } else {
    return dayjs(timeStr).format('MM-DD')
  }
}

// 获取严重程度标签
const getSeverityLabel = (severity) => {
  const labels = {
    'emergency': '紧急',
    'critical': '严重',
    'exception': '异常',
    'warning': '警告',
    'info': '信息'
  }
  return labels[severity] || severity
}

// 获取严重程度标签类型
const getSeverityTagType = (severity) => {
  const types = {
    'emergency': 'danger',
    'critical': 'danger',
    'exception': 'warning',
    'warning': 'warning',
    'info': 'info'
  }
  return types[severity] || 'info'
}

// 获取24小时分布数据
const getHourlyDistribution = () => {
  if (!stats.value.hourly_trend || stats.value.hourly_trend.length === 0) {
    return []
  }
  
  // 按小时聚合数据
  const hourlyMap = {}
  stats.value.hourly_trend.forEach(item => {
    const hour = dayjs(item.hour).hour()
    if (!hourlyMap[hour]) {
      hourlyMap[hour] = 0
    }
    hourlyMap[hour] += item.count
  })
  
  // 生成0-23小时的完整数据
  const result = []
  for (let i = 0; i < 24; i++) {
    result.push({
      hour: i,
      count: hourlyMap[i] || 0
    })
  }
  
  return result
}

// 获取折线图路径
const getLineChartPath = (fillArea = false) => {
  const data = getHourlyDistribution()
  if (data.length === 0) return ''
  
  const maxCount = Math.max(...data.map(h => h.count))
  if (maxCount === 0) return ''
  
  const points = data.map((item, index) => {
    const x = (index / 23) * 1000
    const y = 200 - (item.count / maxCount * 180)
    return { x, y }
  })
  
  // 创建平滑的曲线路径
  let path = `M ${points[0].x} ${points[0].y}`
  
  for (let i = 1; i < points.length; i++) {
    const prev = points[i - 1]
    const curr = points[i]
    const next = points[i + 1]
    
    // 计算控制点以创建平滑曲线
    const tension = 0.3
    let cp1x, cp1y, cp2x, cp2y
    
    if (i === 1) {
      cp1x = prev.x + (curr.x - prev.x) * tension
      cp1y = prev.y + (curr.y - prev.y) * tension
    } else {
      const prevPrev = points[i - 2]
      cp1x = prev.x + (curr.x - prevPrev.x) * tension
      cp1y = prev.y + (curr.y - prevPrev.y) * tension
    }
    
    if (next) {
      cp2x = curr.x - (next.x - prev.x) * tension
      cp2y = curr.y - (next.y - prev.y) * tension
    } else {
      cp2x = curr.x - (curr.x - prev.x) * tension
      cp2y = curr.y - (curr.y - prev.y) * tension
    }
    
    path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${curr.x} ${curr.y}`
  }
  
  // 如果需要填充区域，闭合路径
  if (fillArea) {
    path += ` L ${points[points.length - 1].x} 200 L ${points[0].x} 200 Z`
  }
  
  return path
}

// 刷新仪表板数据
const refreshDashboard = async () => {
  try {
    await Promise.all([
      fetchStats(),
      fetchTrends(),
      fetchHotspots()
    ])
  } catch (error) {
    componentLogger.error('刷新仪表板数据失败:', error)
  }
}

// 切换视图
const toggleView = async () => {
  currentView.value = currentView.value === 'list' ? 'dashboard' : 'list'
  
  // 如果切换到仪表板且还没有数据，则加载数据
  if (currentView.value === 'dashboard' && (trends.value.length === 0 || Object.keys(hotspots.value).length === 0)) {
    await refreshDashboard()
  }
}

// 监听告警类型筛选变化
watch(selectedAlertTypes, async () => {
  if (currentView.value === 'dashboard') {
    await refreshDashboard()
  }
})

// 字段相关辅助方法

const getFieldShowOverflow = (fieldValue) => {
  const overflowFields = [
    'job_id', 'alert_title', 'message', 'escalation_reason'
  ]
  return overflowFields.includes(fieldValue)
}

// 生命周期
onMounted(async () => {
  // 清空选中状态，防止从其他页面返回时显示旧的批量操作卡片
  alertsStore.selectedAlerts = []
  
  // 从localStorage恢复用户选择的字段
  const savedFields = localStorage.getItem('alerts_selected_fields')
  if (savedFields) {
    try {
      selectedFields.value = JSON.parse(savedFields)
    } catch (error) {
      componentLogger.warn('Failed to parse saved fields:', error)
    }
  }
  
  // 初始化数据
  await Promise.all([
    fetchAlerts(),
    fetchStats(),
    fetchTrends(),
    fetchHotspots()
  ])
})
</script>

<style scoped>
.alerts-container {
  padding: 0;
  /* 统一使用纯灰色背景，与其他页面保持一致 */
}

/* 页面头部样式 */
.page-header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  border-radius: 12px;
  overflow: hidden;
  color: #303133;
  min-height: 120px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

.bg-pattern {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 80%, rgba(245, 108, 108, 0.05) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(245, 108, 108, 0.05) 0%, transparent 50%);
  animation: patternMove 30s ease-in-out infinite;
}

.bg-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  opacity: 1;
}

@keyframes patternMove {
  0%, 100% { transform: translateX(0) translateY(0); }
  25% { transform: translateX(-10px) translateY(-5px); }
  50% { transform: translateX(5px) translateY(-10px); }
  75% { transform: translateX(-5px) translateY(5px); }
}

.page-title {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 24px;
  flex: 1;
}

.title-icon {
  position: relative;
}

.page-header .title-icon .icon-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px !important;
  height: 36px !important;
  border-radius: 8px !important;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2) !important;
}

.page-header .title-icon .icon-container:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(245, 108, 108, 0.3) !important;
}

.page-header .title-icon .icon-glow {
  position: absolute;
  top: -4px;
  left: -4px;
  right: -4px;
  bottom: -4px;
  background: linear-gradient(45deg, rgba(245, 108, 108, 0.2), rgba(247, 137, 137, 0.3));
  border-radius: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.page-header .title-icon .icon-container:hover .icon-glow {
  opacity: 1;
}

.title-content {
  flex: 1;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.title-main h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  letter-spacing: -0.3px;
}

.title-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  color: white;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.25);
}

.page-description {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-description .el-icon {
  font-size: 16px;
  color: #909399;
}

.title-meta {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 12px;
  font-weight: 500;
}

.meta-item .el-icon {
  font-size: 16px;
}

/* 统计卡片样式 */
.page-stats {
  position: relative;
  z-index: 1;
  display: flex;
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 120px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stat-card:hover {
  background: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #f56c6c;
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-icon {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.stat-card.total .stat-icon {
  background: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.stat-card.active .stat-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.stat-card.resolved .stat-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stat-card.escalated .stat-icon {
  background: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  color: #909399;
  font-weight: 500;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 24px;
}

.search-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.search-title .el-icon {
  color: #409eff;
}

.search-form {
  margin: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form-fields {
  display: flex;
  gap: 16px;
  flex: 1;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-form-fields .el-form-item {
  margin-bottom: 0;
}

.search-form-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-btn, .reset-btn, .refresh-btn, .field-btn {
  border-radius: 8px;
  font-weight: 500;
}

.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

/* 字段设置面板 */
.field-selector-panel {
  border-top: 1px solid #e4e7ed;
  background: #f8f9fa;
  padding: 20px;
}

.field-panel-enter-active,
.field-panel-leave-active {
  transition: all 0.3s ease;
}

.field-panel-enter-from,
.field-panel-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.field-sorter {
  margin-bottom: 20px;
}

.sorter-header {
  margin-bottom: 16px;
}

.sorter-header h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.sorter-description {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.field-list-sortable {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.field-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.field-item.field-disabled {
  opacity: 0.6;
  background: #f5f7fa;
}

.field-drag-handle {
  cursor: move;
  color: #909399;
  font-size: 16px;
}

.drag-icon {
  font-family: monospace;
  line-height: 1;
}

.field-checkbox {
  flex: 1;
}

.field-label {
  font-weight: 500;
  margin-right: 4px;
}

.required-mark {
  color: #f56c6c;
  font-weight: bold;
}

.field-group-tag {
  flex-shrink: 0;
}

.field-sort-controls {
  display: flex;
  gap: 4px;
}

.field-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 表格区域样式 */
.table-section {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-title .el-icon {
  color: #409eff;
}

.table-info {
  display: flex;
  gap: 8px;
}

.table-container {
  width: 100%;
  overflow-x: visible;
  margin: 0 auto;
  border-radius: 12px;
  background: #fff;
}

/* 增强表格样式 */
.enhanced-table {
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.table-container .el-table {
  width: 100% !important;
  border-radius: 16px;
  overflow: hidden;
  background: #fff;
}

.table-container .el-table__header {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.table-container .el-table th {
  background: transparent !important;
  border-bottom: none;
  padding: 6px 12px;
  vertical-align: middle;
}

.table-container::-webkit-scrollbar {
  height: 8px;
}

.table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表格列头样式 */
/* 简化列标题样式 - 纯中文 */
.column-header-simple {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  text-align: left;
  padding: 0;
  white-space: nowrap !important;
}

/* 确保表格头部不换行 - 全局设置 */
.enhanced-table :deep(.el-table__header-wrapper) th {
  white-space: nowrap !important;
}

.enhanced-table :deep(.el-table__header-wrapper) th .cell {
  white-space: nowrap !important;
  overflow: visible !important;
  display: flex !important;
  align-items: center !important;
  flex-wrap: nowrap !important;
}

/* 排序图标容器不换行 */
.enhanced-table :deep(.el-table__header-wrapper) th .caret-wrapper {
  flex-shrink: 0 !important;
  margin-left: 4px !important;
}

/* 表格内容样式 */
.field-content {
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.field-content:hover {
  background: rgba(64, 158, 255, 0.05);
}

/* 可复制字段样式 */
.copyable,
.copyable-field {
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 6px;
  padding: 4px 8px;
  margin: -4px -8px;
}

.copyable:hover,
.copyable-field:hover {
  background: rgba(64, 158, 255, 0.1);
  transform: scale(1.02);
}

.copy-hint {
  position: absolute;
  top: 50%;
  right: 8px;
  transform: translateY(-50%);
  opacity: 0;
  transition: all 0.3s ease;
  background: rgba(64, 158, 255, 0.9);
  color: white;
  padding: 4px 6px;
  border-radius: 4px;
  font-size: 12px;
  pointer-events: none;
  z-index: 10;
}

.copyable:hover .copy-hint,
.copyable-field:hover .copy-hint {
  opacity: 1;
  transform: translateY(-50%) translateX(-4px);
}

.copy-hint::before {
  content: '';
  position: absolute;
  right: -4px;
  top: 50%;
  transform: translateY(-50%);
  border: 4px solid transparent;
  border-left-color: rgba(64, 158, 255, 0.9);
}

/* 作业名称样式优化 */
/* 作业名称列样式 - 新版复制按钮 */
.job-name-cell-alert {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}

.job-name-text-alert {
  flex: 1;
  white-space: nowrap;
  font-size: 14px;
  font-weight: 400;
  color: #303133;
  line-height: 1.4;
}

.job-name-cell-alert .copy-btn-alert {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  padding: 0;
  opacity: 0; /* 默认隐藏 */
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

.job-name-cell-alert:hover .copy-btn-alert {
  opacity: 1; /* 悬停时显示 */
}

.job-name-cell-alert .copy-btn-alert:hover {
  transform: scale(1.1); /* 悬停时放大 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.job-name-cell-alert .copy-btn-alert:active {
  transform: scale(0.95); /* 点击时缩小 */
}

/* 旧的作业名称样式 - 保留用于兼容 */
.job-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
}

.job-name.copyable {
  padding: 8px 32px 8px 0;
}

.job-info {
  flex: 1;
  min-width: 0;
  margin-right: 8px;
}

.job-title {
  font-size: 14px;
  font-weight: 400;
  color: #303133;
  margin-bottom: 2px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 可复制字段的通用样式 */
.copyable-field {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  min-height: 24px;
  padding: 4px 32px 4px 8px;
}

.copyable-field .el-text,
.copyable-field .el-tag {
  flex: 1;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  white-space: nowrap;
  justify-content: flex-start;
  align-items: center;
  min-width: 200px;
}

.action-buttons .el-button {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-buttons .el-button:active {
  transform: translateY(0) scale(0.98);
}

.action-buttons .el-button--primary {
  background: linear-gradient(135deg, #409EFF 0%, #66B3FF 100%);
  border: none;
}

.action-buttons .el-button--success {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
}

.action-buttons .el-button--warning {
  background: linear-gradient(135deg, #E6A23C 0%, #F0C78A 100%);
  border: none;
}

.action-buttons .el-button--danger {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
  border: none;
}

.action-buttons .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

.table-container .el-table td {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  padding: 12px;
  font-size: 14px;
  font-weight: 400;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

/* 表格行样式 */
.enhanced-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.enhanced-table :deep(.el-table__row:hover) {
  background: rgba(64, 158, 255, 0.05) !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 状态行悬停效果 */
.row-success:hover td {
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.05) 0%, rgba(133, 206, 97, 0.05) 100%) !important;
}

.row-danger:hover td {
  background: linear-gradient(135deg, rgba(245, 108, 108, 0.05) 0%, rgba(247, 137, 137, 0.05) 100%) !important;
}

.row-info:hover td {
  background: linear-gradient(135deg, rgba(144, 147, 153, 0.05) 0%, rgba(177, 179, 184, 0.05) 100%) !important;
}


/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 0;
  padding: 24px 32px;
  background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
  border-top: 1px solid rgba(228, 231, 237, 0.6);
  border-radius: 0 0 16px 16px;
  position: relative;
}

.pagination::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, rgba(64, 158, 255, 0.2) 50%, transparent 100%);
}

/* 为告警页面添加增强分页样式 */
.enhanced-pagination {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px 24px;
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04),
    inset 0 1px 0 rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.enhanced-pagination:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 40px rgba(0, 0, 0, 0.12),
    0 4px 16px rgba(0, 0, 0, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.95);
}

/* 合并的分页控制容器 */
.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(245, 108, 108, 0.08);
  border: 1px solid rgba(245, 108, 108, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(245, 108, 108, 0.12);
  border-color: rgba(245, 108, 108, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(245, 108, 108, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #f56c6c;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-icon {
  font-size: 12px;
  color: #f56c6c;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-icon.expanded {
  transform: rotate(180deg);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-stats {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  }
}

@media (max-width: 768px) {
  .alerts-container {
    padding: 0 10px;
  }
  
  .page-title {
    padding: 20px;
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .title-main h1 {
    font-size: 24px;
  }
  
  .page-stats {
    padding: 0 20px 20px;
    grid-template-columns: 1fr;
  }
  
  .search-form-fields {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form-actions {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .field-item {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .field-sort-controls {
    order: -1;
    width: 100%;
    justify-content: center;
  }
}

/* 强制覆盖Element Plus样式 */
.table-container .el-table th .column-header .header-icon {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 18px !important;
  height: 18px !important;
  background: rgba(64, 158, 255, 0.08) !important;
  border-radius: 3px !important;
  color: #409eff !important;
  font-size: 10px !important;
  flex-shrink: 0 !important;
  transition: all 0.3s ease !important;
}

.table-container .el-table th .column-header .header-title {
  font-size: 12px !important;
  font-weight: 600 !important;
  color: #303133 !important;
  margin-bottom: 1px !important;
  line-height: 1.2 !important;
  letter-spacing: 0.2px !important;
  white-space: nowrap !important;
}

.table-container .el-table th .column-header .header-subtitle {
  font-size: 9px !important;
  color: #909399 !important;
  font-weight: 400 !important;
  line-height: 1.1 !important;
  text-transform: uppercase !important;
  letter-spacing: 0.3px !important;
  white-space: nowrap !important;
}

/* 仪表板样式 */
.dashboard-section {
  margin-bottom: 24px;
}

/* 告警类型筛选器 */
.dashboard-filter-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.dashboard-filter {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.filter-label .el-icon {
  color: #409eff;
}

.alert-type-checkboxes {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.alert-type-checkboxes .el-checkbox {
  margin-right: 0;
}

.filter-actions {
  display: flex;
  gap: 8px;
}

.dashboard-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.dashboard-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.chart-container {
  padding: 16px;
  overflow-y: auto;
}

/* 严重程度分布图 */
.severity-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.severity-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.severity-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.severity-count {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.severity-bar {
  width: 100%;
  height: 10px;
  background: #f5f7fa;
  border-radius: 5px;
  overflow: hidden;
}

.severity-fill {
  height: 100%;
  border-radius: 5px;
  transition: width 0.5s ease;
}

.severity-fill.severity-emergency {
  background: linear-gradient(90deg, #f56c6c 0%, #f78989 100%);
}

.severity-fill.severity-critical {
  background: linear-gradient(90deg, #e6a23c 0%, #f0b65f 100%);
}

.severity-fill.severity-exception {
  background: linear-gradient(90deg, #e6a23c 0%, #ebb563 100%);
}

.severity-fill.severity-warning {
  background: linear-gradient(90deg, #409eff 0%, #66b3ff 100%);
}

.severity-fill.severity-info {
  background: linear-gradient(90deg, #909399 0%, #b1b3b8 100%);
}

/* 告警类型分布图 */
.type-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.type-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.type-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.type-count {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.type-bar {
  width: 100%;
  height: 10px;
  background: #f5f7fa;
  border-radius: 5px;
  overflow: hidden;
}

.type-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff 0%, #66b3ff 100%);
  border-radius: 5px;
  transition: width 0.5s ease;
}

/* 24小时折线图 */
.hourly-line-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chart-grid {
  position: relative;
  flex: 1;
  min-height: 200px;
}

.y-axis-lines {
  position: absolute;
  top: 10px;
  left: 0;
  right: 0;
  bottom: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  pointer-events: none;
}

.grid-line {
  width: 100%;
  height: 1px;
  background: #e4e7ed;
}

.line-container {
  position: absolute;
  top: 10px;
  left: 0;
  right: 0;
  bottom: 10px;
}

.line-svg {
  width: 100%;
  height: 100%;
}

.data-point {
  cursor: pointer;
  transition: all 0.2s ease;
}

.data-point:hover {
  r: 6;
  fill: #66b3ff;
  filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.3));
}

.x-axis-labels {
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
  margin-top: 8px;
}

.x-label {
  font-size: 11px;
  color: #909399;
  font-weight: 500;
}

/* 作业热点图 */
.hotspot-chart {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.job-hotspot-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.job-rank {
  min-width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  color: white;
  border-radius: 50%;
  font-weight: 600;
  font-size: 12px;
}

.job-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.job-name-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.job-name {
  flex: 1;
  font-size: 13px;
  color: #303133;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.job-tags {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}

.job-bar {
  width: 100%;
  height: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}

.job-fill {
  height: 100%;
  background: linear-gradient(90deg, #67c23a 0%, #85ce61 100%);
  border-radius: 4px;
  transition: width 0.5s ease;
}

.job-fill.has-active {
  background: linear-gradient(90deg, #f56c6c 0%, #f78989 100%);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-title .el-icon {
  color: #409eff;
}

/* 趋势图表样式 */
.trend-content {
  padding: 16px 0;
}

.trend-item {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
  padding: 8px 0;
}

.trend-time {
  min-width: 80px;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.trend-bars {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.bar-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bar-label {
  min-width: 40px;
  font-size: 11px;
  color: #606266;
}

.bar-bg {
  flex: 1;
  height: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.bar-fill.total {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
}

.bar-fill.resolved {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.bar-value {
  min-width: 24px;
  font-size: 11px;
  color: #303133;
  font-weight: 600;
  text-align: right;
}

/* 热点分析样式 */
.hotspot-content {
  padding: 16px 0;
}

.hotspot-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.hotspot-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.hotspot-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.hotspot-item:hover {
  background: #fff;
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.hotspot-name {
  font-size: 13px;
  color: #303133;
  font-weight: 500;
  flex: 1;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hotspot-stats {
  display: flex;
  gap: 6px;
  align-items: center;
}

/* 批量操作栏 - 紧凑样式 */
.batch-actions-bar {
  margin-bottom: 20px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(245, 108, 108, 0.3);
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  animation: slideInDown 0.3s ease;
}

.batch-info-compact {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: white;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
}

.batch-info-compact .selected-icon {
  font-size: 16px;
}

.batch-info-compact strong {
  font-weight: 600;
  margin: 0 2px;
}

.batch-divider {
  color: white;
  font-size: 16px;
  opacity: 0.6;
  margin: 0 4px;
}

.batch-buttons-compact {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.batch-btn-compact {
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  color: #fff;
}

.batch-btn-compact .el-icon {
  margin-right: 4px;
  font-size: 16px;
}

.batch-btn-compact:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

/* 状态指示器样式 */
.status-container {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.status-indicator {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.indicator-active {
  background: #f56c6c;
  box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.7);
}

.indicator-resolved {
  background: #67c23a;
  box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
}

.indicator-escalated {
  background: #e6a23c;
  box-shadow: 0 0 0 0 rgba(230, 162, 60, 0.7);
}

.indicator-silenced {
  background: #909399;
  box-shadow: 0 0 0 0 rgba(144, 147, 153, 0.7);
}

@keyframes pulse {
  0% {
    transform: scale(0.95);
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0.7);
  }
  70% {
    transform: scale(1);
    box-shadow: 0 0 0 6px rgba(0, 0, 0, 0);
  }
  100% {
    transform: scale(0.95);
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
  }
}

/* 仪表板过渡动画 */
.dashboard-enter-active,
.dashboard-leave-active {
  transition: all 0.3s ease;
}

.dashboard-enter-from,
.dashboard-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

/* 搜索操作区域样式 */
.search-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 行状态样式增强 */
.row-warning {
  position: relative;
}

.row-warning::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .dashboard-section .el-row {
    flex-direction: column;
  }
  
  .dashboard-section .el-col {
    width: 100% !important;
    margin-bottom: 16px;
  }
  
  .trend-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .batch-info {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .batch-buttons {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>
